package handlers

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"tvseries-hub/models"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	img := c.PostForm("img")
	content := c.PostForm("content")

	if title == "" || img == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	film := models.Film{
		Title:   title,
		Img:     img,
		Content: content,
	}

	err := models.DB.Create(&film).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件数据获取失败",
		})
		return
	}

	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件上传失败",
		})
		return
	}

	url := "http://" + c.Request.Host + "/" + path
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "文件上传成功",
		"data": url,
	})
	return

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))

	query := models.DB.Model(&models.Film{})

	var count int64
	query.Count(&count)

	offset := (page - 1) * size
	var file []models.Film

	err := query.Offset(offset).Limit(size).Find(&file).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"file":  file,
		},
	})
	return

}
